<?php

namespace mpend\modules\search\models;

use Yii;

/**
 * 统一搜索模型
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class KeywordUnifiedSearch extends \mpend\models\searchs\ArticleSearch {

    use \common\traits\UnifiedKeyword;

    /**
     * 构建查询query
     * @return \common\db\ActiveQuery
     */
    public function buildQuery($alias = 't') {
        $this->validate();

        $libs = $this->getLibs();
        $keywords = $this->getWords();
        $query = parent::buildQuery($alias);
        if ($alias) {
            $alias .= '.';
        }

        //Union关键词库
        if (!empty($libs)) {
            $libQuery = clone $query;
            $query->union($libQuery->innerJoinWith('keywords key')->andWhere(['key.lib_id' => $libs]));
        }

        //模糊关键词
        if (!empty($keywords)) {
            $likewhere = ['or'];
            foreach ($keywords as $word) {
                $likewhere[] = ['like', $alias . 'title', $word];
                $likewhere[] = ['like', $alias . 'description', $word];
            }
            $query->andFilterWhere($likewhere);
        }

        $query->debug();
        return $query;
    }

}
